﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotaHelp.Models;
using DotaHelp.Helpers;
using System.ServiceModel.Syndication;

namespace DotaHelp.Controllers
{
    
    public class RecordsController : Controller
    {
        DotaModel model = new DotaModel();

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            model.Dispose();
            
        }

        public ActionResult List()
        {
            return View(model.Records.Where(r=>!r.IsDeleted).OrderByDescending(r=>r.Date));
        }

        public ActionResult Add()
        {
            ViewBag.Author = Request.GetUserName();
            ViewBag.Heroes = model.Heroes.ToArray();
            return View();
        }

        [HttpPost]
        public ActionResult Add(string author, string password, string comment, string data)
        {
            Response.SaveUserName(author);

            var r = new Record()
            {
                IpAddress = Request.ServerVariables["REMOTE_ADDR"],
                Date = DateTime.UtcNow.NowByAstana(),
                Raiting = 0,
                Author = ControllerContext.HttpContext.PrepareUserName(author),
                Comment = comment,
                Password = password,
                IsDeleted = false,
                Data = data
            };

            model.Records.AddObject(r);
            model.SaveChanges();
            return RedirectToAction("List");
        }

        [Sitemap(typeof(Record), "Date")]
        public ActionResult Details(int id)
        {
            return View("Add", model.Records.First(r => r.Id == id));
        }

        [Authorize(Roles = "Admin")]
        public void Delete(int id)
        {
            var r = model.Records.First(i => i.Id == id);
            r.IsDeleted = true;
            model.SaveChanges();
        }

        [ChildActionOnly]
        public string Rating(int id, bool isPlus)
        {
            var r = model.Records.First(p => p.Id == id);
            r.Raiting += isPlus ? 1 : -1;
            model.SaveChanges();
            return r.Raiting.ToString();
        }

        [ChildActionOnly]
        [Rss]
        public IEnumerable<SyndicationItem> Rss()
        {
            var url = new UrlHelper(Request.RequestContext);

            foreach (var c in model.Records.OrderByDescending(_ => _.Date).Take(50))
            {
                yield return new SyndicationItem("Запись", c.Comment, new Uri(url.GetBaseUrl(), url.Action("Details", "Records", new { id = c.Id })), "r" + c.Id, c.Date);
            }
        } 
    }
}
